# -*- coding: utf-8 -*-
#!/usr/bin/env python
# @author: lipeng
"""assess the image's brigthness and quality
"""
import os
import cv2
import math
import numpy as np

# calc average value(H, S, V)
def get_brightness_value(img_bgr):
    img_hsv = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2HSV)
    _, _, img_v = cv2.split(img_hsv)
    average_v = np.sum(np.reshape(img_v, (img_v.size,))) / img_v.size
    return average_v

# evaluate the quality of img by ssim(structure similarity)
def get_quality_score(img, len_s = 11):
    img = cv2.resize(img, (96, 96), 3)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    #img = img.astype(np.float)-np.mean(img)
    X_org, Y_org = img.shape
    res_list = []
    for i in range(0, int(X_org), int(X_org / len_s)+3):
        for j in range(0, int(Y_org), int(Y_org / len_s)+3):
            res_list.append(ssimFunction(img[i:i + len_s, j:j + len_s]))
    res_list = np.array(res_list)

    res_list_sort = res_list[np.lexsort(-res_list.T)]
    res_list = res_list_sort[:, :1]
    res = np.mean(res_list[:10])
    if res < 0.0:
        res = 0.0
    return 1 - res

def entropyFunc(img):
    res = 0
    tmp = [0] * 256
    img_list = []
    for i in range(len(img)):
        img_list.extend(map(int, img[i]))
    img_list_set = set(img_list)
    for i in img_list_set:
        tmp[i] = float(img_list.count(i))/ 256

    np.random.shuffle(tmp)
    for i in range(len(tmp)):
        if (tmp[i] == 0):
            res = res
        else:
            res = float(res - i * (math.log(tmp[i]) / math.log(2.0)))
            #res = float(res - tmp[i] * (math.log(tmp[i]) / math.log(2.0)))
    return res

def ssimFunction(img):
    x, y = img.shape
    resEntropy = entropyFunc(img)
    TR = cv2.GaussianBlur(img, (5,5),3)
    G  = cv2.Sobel(img,cv2.CV_16S,2,2)/5
    Gr = cv2.Sobel(TR,cv2.CV_16S,2,2)/5
    Ux = np.mean(G)
    Uy = np.mean(Gr)
    Vx = np.var(G)
    Vy = np.var(Gr)

    Vxy = (1 / (x * y - 1)) * np.sum((G - Ux) * (Gr - Uy))
    R = 255
    K1 = 0.03
    K2 = 0.01
    c1 = (K1 * R) ** 2
    c2 = (K2 * R) ** 2
    # -SSIM
    A1 = 2 * Ux * Uy + c1
    A2 = 2 * Vxy + c2
    B1 = Ux ** 2 + Uy ** 2 + c1
    B2 = Vx  + Vy  + c2
    SSIM = (A1 * A2) / (B1 * B2)

    return SSIM, resEntropy
